package com.zs.controller;

import jakarta.faces.annotation.RequestParameterMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/*
* 接收文件：
* 1 导入依赖
*   <dependency>
*       <groupId>commons-fileupload</groupId>
*       <artifactId>commons-fileupload</artifactId>
*       <version>1.3.1</version>
*   </dependency>
* 2 文件上传处理器，文件流变成文件对象
*
*    <bean id="multipartResolver"
*          class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
*    </bean>
* 3 spring6+ 本班额额外配置大小限制
*   <multipart-config>
*      <!-- 定义文件上传时所需要的最大值，单位为字节 -->
*      <max-file-size>10485760</max-file-size>
*      <!-- 定义单个上传文件的最大值，超过此大小的文件会写入到硬盘中 -->
*      <max-request-size>20971520</max-request-size>
*      <!--  定义内存中存储的最大值，超过此大小的文件会写入到硬盘中    -->
*      <file-size-threshold>5242880</file-size-threshold>
*    </multipart-config>
*  4. handler进行文件的接受，文件类型为MultiPartFile 变量
*     1 接收文件 形参列表
*     2 文件的转存和地址拼接，MultipartFile.getOriginalFilename() .getBytes() .getName();
*     3 文件地址存储到数据库
*
* */
@RestController
@RequestMapping("upload")
//@EnableWebMvc
public class FileController {

    @PostMapping("file")
    public String uploadFile(@RequestParam(defaultValue = "account") String name,
                             @RequestParam String password,
                             @RequestParam("file") MultipartFile image) throws IOException {
        System.out.println("name:" + name);
        System.out.println("password:" + password);
        System.out.println("file:" + image);
        String filename = image.getOriginalFilename();
        System.out.println("filename:" + filename);
        String httpKey = image.getName();
        System.out.println("httpKey:" + httpKey);
        byte[] bytes = image.getBytes();
        System.out.println(bytes.length);
        return "上传成功";
    }
    @Autowired
    private ServletContext servletContext;
    @GetMapping("download")
    public void download(HttpServletResponse  response) throws IOException {
    // 1.读取项目下的文件的输入流
    String realPath = servletContext.getRealPath("/images/111.jpg");
    FileInputStream fis = new FileInputStream(realPath);
    // 2. 设置一些参数
        response.setHeader("Content-Disposition","attachment;filename=111.jpg");
    // 3. 使用响应字节流输出写回文件即可
    ServletOutputStream ops = response.getOutputStream();
    byte[] buffer = new byte[8 * 1024];
    int len = -1;
    while ((len = fis.read(buffer)) != -1){
        ops.write(buffer,0,len);
    }
    if (fis != null){
        fis.close();
    }


    }


}
